/*
 * This is a standard pager activity that hosts AgentFragment and enables
 * paging between agents
 */

package sk.stuba.fei.ut.snmpmanager;

import java.util.ArrayList;
import java.util.UUID;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

public class AgentPagerActivity extends FragmentActivity implements
		AgentFragment.Callbacks
{
	private ViewPager mViewPager;
	private ArrayList<Agent> mAgents;

	@Override
	public void onCreate( Bundle onSavedInstanceState )
	{
		super.onCreate( onSavedInstanceState );

		mViewPager = new ViewPager( this );
		mViewPager.setId( R.id.viewPager );
		setContentView( mViewPager );

		System.setProperty( "java.net.preferIPv4Stack", "true" );
		System.setProperty( "java.net.preferIPv6Addresses", "false" );

		mAgents = AgentManager.get( this ).getAgents();
		FragmentManager fm = getSupportFragmentManager();
		// implementing paging
		mViewPager.setAdapter( new FragmentStatePagerAdapter( fm )
		{
			@Override
			public int getCount()
			{
				// return size of ArrayList
				return mAgents.size();
			}

			@Override
			public Fragment getItem( int arg0 )
			{
				// get next or previous Agent with each swipe
				Agent agent = mAgents.get( arg0 );
				return AgentFragment.newInstance( agent.getID() );

			}
		} );

		// change ActionBar title when user swipes
		mViewPager
				.setOnPageChangeListener( new ViewPager.OnPageChangeListener()
				{

					@Override
					public void onPageSelected( int arg0 )
					{
						Agent agent = mAgents.get( arg0 );
						if ( agent.getTitle() != null )
							setTitle( agent.getTitle() );
					}

					@Override
					public void onPageScrolled( int arg0, float arg1, int arg2 )
					{
					}

					@Override
					public void onPageScrollStateChanged( int arg0 )
					{
					}
				} );

		// display Agent by ID
		UUID agentID = ( UUID ) getIntent().getSerializableExtra(
				AgentFragment.EXTRA_AGENT_ID );
		for ( int i = 0; i < mAgents.size(); i++ )
		{
			if ( mAgents.get( i ).getID().equals( agentID ) )
			{
				mViewPager.setCurrentItem( i );
				break;
			}
		}

	}

	public void onAgentUpdated( Agent agent )
	{
		/*
		 * In pager activity we don't use two-pane detail so we update the List
		 * after every onResume()
		 */
	}

}
